package openai

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/EDDYCJY/go-gin-example/models"
	"github.com/EDDYCJY/go-gin-example/pkg/app"
	"github.com/EDDYCJY/go-gin-example/pkg/openai/aijieyun/pkg/services/aecs"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/gin-gonic/gin"
)

type DescribeInstancesinfoRequest struct {
	*requests.RpcRequest
	PageNumber int64
	PageSize   int64
}

func DescribeInstancesinfo(c *gin.Context) {
	appG := app.Gin{C: c}

	client := aecs.DefaultClient

	request := DescribeInstancesinfoRequest{RpcRequest: &requests.RpcRequest{}}
	var userID = uint64(c.GetInt64("user_id"))

	fmt.Println("userID:", userID)
	if request.PageSize == 0 {
		request.PageSize = 10
	}

	var offset int64
	if request.PageNumber <= 1 {
		offset = 0
	} else {
		offset = (request.PageNumber - 1) * request.PageSize
	}
	rentOrders := &[]models.RentOrder{}
	var t_now = time.Now().UTC()
	db := models.GetDB()
	err := db.Model(&models.RentOrder{}).Debug().
		Where("user_id= ?", userID).
		Where("rent_start_time <= ? and rent_end_time > ?", t_now, t_now).
		Offset(offset).Limit(request.PageSize).Scan(rentOrders).Error
	// err := models.GetDB().Model(&models.RentOrder{}).Debug().Where(&models.RentOrder{UserId: userID, RentType: models.PaymentTypeRentAiJiYun}).Where("rent_start_time < rent_end_time").Offset(offset).Limit(request.PageSize).Scan(rentOrder).Error
	fmt.Printf("rent order:%+v", *rentOrders)
	if err != nil {
		appG.ResponseError(-1, err.Error())
		return
	}
	//for 遍历查询taskID

	instanceIds := make([]string, len(*rentOrders))
	for i, v := range *rentOrders {
		instanceIds[i] = v.TaskId
	}

	rpcRequest := request.RpcRequest
	rpcRequest.InitWithApiInfo("Ecs", "2014-05-26", "DescribeInstancesInfo", "ecs", "openAPI")

	m := rpcRequest.GetQueryParams()

	jsonBytes, err := json.Marshal(instanceIds)
	if err != nil {
		fmt.Println(err)
		return
	}
	jsonString := string(jsonBytes)
	m["instanceIds"] = jsonString

	response, err := client.DescribeInstancesInfo(rpcRequest)

	if err != nil {
		appG.ResponseError(-1, err.Error())
		return
	}

	// m := request.GetQueryParams()

	if err != nil {
		// c.JSON(400, gin.H{"response": "", "err": err.Error()})
		appG.ResponseError(-1, err.Error())

		return
	}

	// 将响应转换为所需的格式
	var responseData map[string]interface{}
	jsonStr := response.GetHttpContentString()
	err = json.Unmarshal([]byte(jsonStr), &responseData)
	if err != nil {
		appG.ResponseError(-1, err.Error())
		return
	}

	appG.ResponseSuccess(gin.H{"response": responseData})
}
